#ifndef SERIALMANAGER_H
#define SERIALMANAGER_H

#include <QObject>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QTimer>
#include <QVariantMap>
#include <QVariant>
#include <QVariantList>


class SerialManager : public QObject
{
    Q_OBJECT

public:

    explicit SerialManager(QObject *parent = nullptr);

    Q_PROPERTY(bool connected READ connected NOTIFY connectedChanged)
    Q_PROPERTY(int rxCount READ rxCount WRITE setRxCount NOTIFY rxCountChanged)
    Q_PROPERTY(int txCount READ txCount WRITE setTxCount NOTIFY txCountChanged)
    Q_PROPERTY(QVariantList  availablePorts READ availablePorts NOTIFY availablePortsChanged)

    void  setRxCount(const int &cnt);
    void  setTxCount(const int &cnt);
    // QStringList availablePorts() const  { return m_ports; }

    Q_INVOKABLE QVariantList  availablePorts() const  { return m_ports; }
    Q_INVOKABLE void setPort(const QString &portName);
    Q_INVOKABLE void setBaudRate(int baudRate);
    Q_INVOKABLE void openPort();
    // Q_INVOKABLE void openPort(const QString &portName, int baudRate);
    Q_INVOKABLE void closePort();
    Q_INVOKABLE void writeData(const QByteArray &data);
    // Q_INVOKABLE void sendData(const QString &data);

    // //刷新接口
    // Q_INVOKABLE void refreshPorts();

    bool isOpen() const;   //加上这个方法

    bool connected() const { return m_serial.isOpen(); }
    int rxCount() const { return m_rxCount; }
    int txCount() const { return m_txCount; }

signals:
    void availablePortsChanged();  //通知 QML model 变更
    void connectedChanged();
    void closeSerialmanager();
    void rxCountChanged();
    void txCountChanged();
    void dataReceived(const QString &data);
    void dataSend(const QString &data);

private slots:
    void handleReadyRead();
    void refreshPorts();

private:
    QSerialPort m_serial;
    int m_rxCount = 0;
    int m_txCount = 0;

    QString m_portName;
    int m_baudRate;
    /*QStringList*/QVariantList m_ports;  // 缓存串口列表

    QTimer m_timer;
};

#endif // SERIALMANAGER_H
